/* TCP echo server end*/
#include "z_http.h"
#define MAXPENDING 256

void HandleClient(int sock){
	pid_t self_pid = getpid();
	fprintf(stdout,"[Children Process] pid= %d",self_pid);
	char buffer[BUFFSIZE];
	char * ptr = buffer;
	int received = 0, bytes = -1,c_s = BUFFSIZE;
	while ((bytes = recv(sock, ptr, BUFFSIZE-c_s, 0)) > 0) {
		received += bytes;
		ptr		 += bytes; 
	}

	buffer[received] = '\0';
	fprintf(stdout,"%s",buffer);
	char echobuffer[BUFFSIZE];
	size_t echolen = strlen(echobuffer);
	while (send(sock, echobuffer, echolen, 0) != echolen) 
		Die("Failed to send bytes to client");
	close(sock);
}

int main(int argc, char ** argv){
	int serversock, clientsock;
	struct sockaddr_in echoserver, echoclient;
	size_t clientlen = sizeof(echoclient);

	if (argc != 2){
		fprintf(stderr, "USAGE:echoserver <port>\n");
		exit(1);
	}
	/* Create the TCP sock */
	if ((serversock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ Die("Failed to create socket"); }
	/* Constuct the server sockaddr_in structure */
	memset(&echoserver, 0, sizeof(echoserver));
	echoserver.sin_family = AF_INET;
	echoserver.sin_addr.s_addr = htonl(INADDR_ANY);
	echoserver.sin_port = htons(atoi(argv[1]));

	/* Bind the server socket */
	if (bind(serversock, (struct sockaddr *) &echoserver, sizeof(echoserver)) < 0){ Die("Failed to bind the server socket"); }
	/* Listen on the server socket */
	if (listen(serversock, MAXPENDING) < 0){ Die("Failed to listen on server socket"); }

	/* Run until cancelled */
	while (1){
		/* Wait for client connection */
		if ((clientsock = accept(serversock, (struct sockaddr *) &echoclient, &clientlen)) < 0){
			Die("Failed to accept client connection");
		}
		fprintf(stdout, "Client connected: %s\n", inet_ntoa(echoclient.sin_addr));
		pid_t pid = fork();
		if (pid == 0){
			HandleClient(clientsock);
		}else
		if (pid < 0)
			Die("fork failed");
		else
		if (pid > 0)
			puts("[Father Process]");
	}
}

